<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
		<el-form-item label="学校" prop="sbXxid">
		  <el-select v-model="queryParams.sbXxid" @change="handleQuery" placeholder="请选择学校" :disabled="isXxidFlag">
		    <el-option
		      v-for="d in dept_self"
		      :key="d.value"
		      :label="d.label"
		      :value="d.value"
		    />
		  </el-select>
		</el-form-item>
      <el-form-item label="客户端ID" prop="sbClientid">
        <el-input
          v-model="queryParams.sbClientid"
          placeholder="请输入客户端ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="sbName">
        <el-input
          v-model="queryParams.sbName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否在线" prop="sbIszx">
        <el-select v-model="queryParams.sbIszx" placeholder="请选择是否在线">
          <el-option
            v-for="dict in tc_zxzt"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否启用" prop="sbIsqy">
        <el-select v-model="queryParams.sbIsqy" @change="handleQuery" placeholder="请选择是否启用">
          <el-option
            v-for="dict in tc_qyzt"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
	  
	  
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="RefreshRight"
          @click="handleTB" 
        >同步设备列表</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['tc:shebei:add']"
        >新增</el-button>
      </el-col>
<!-- 	  
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="RefreshRight"
          @click="handleTB" 
        >同步设备</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['tc:shebei:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tc:shebei:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['tc:shebei:export']"
        >导出</el-button>
      </el-col>
	  -->
	  
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="shebeiList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
	  <el-table-column type="index" label="序号" width="55" />
      <!-- <el-table-column label="设备ID" align="center" prop="id" /> -->
	  <!-- :show-overflow-tooltip="true" -->
      <el-table-column :show-overflow-tooltip="true" label="客户端ID" align="center" prop="sbClientid" min-width="150" />
      <el-table-column label="设备名称" align="center" prop="sbName" />
      <el-table-column label="登录用户" align="center" prop="sbLoginuser" />
      <el-table-column :show-overflow-tooltip="true" label="订阅主题" align="center" prop="sbTopic" />
      <el-table-column :show-overflow-tooltip="true" label="IP" align="center" prop="sbIp" />
      <el-table-column :show-overflow-tooltip="true" label="连接节点" align="center" prop="sbJiedian" />
      <el-table-column label="是否在线" align="center" prop="sbIszx">
        <template #default="scope">
          <dict-tag :options="tc_zxzt" :value="scope.row.sbIszx"/>
        </template>
      </el-table-column>
      <el-table-column label="是否启用" align="center" prop="sbIsqy">
        <template #default="scope">
          <dict-tag :options="tc_qyzt" :value="scope.row.sbIsqy"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="sbCreatetime" width="140">
        <template #default="scope">
          <span>{{ parseTime(scope.row.sbCreatetime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="sbUpdatetime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.sbUpdatetime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  width="330">
        <template #default="scope">
		  <el-button link type="primary" icon="RefreshLeft" @click="handleUpdateState(scope.row)">更新状态</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate2(scope.row)" v-hasPermi="['tc:shebei:edit']">绑定项目</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['tc:shebei:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['tc:shebei:remove']">删除</el-button>
	<!-- 	  
	
	<el-table-column label="项目分类" align="center" prop="sbTctype" />
		  -->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="shebeiRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户端ID" prop="sbClientid">
          <el-input v-model="form.sbClientid" @input="clitendidInput" placeholder="请输入客户端ID" :disabled="formFlag" />
        </el-form-item>
        <el-form-item label="设备名称" prop="sbName">
          <el-input v-model="form.sbName" placeholder="请输入设备名称"/>
        </el-form-item>
        <el-form-item label="登录用户" prop="sbLoginuser">
          <el-input v-model="form.sbLoginuser" placeholder="请输入登录用户" :disabled="formFlag" />
        </el-form-item>
        <el-form-item label="订阅主题" prop="sbTopic">
          <el-input v-model="form.sbTopic" placeholder="请输入订阅主题" :disabled="formFlag" />
        </el-form-item>
        <el-form-item label="协议类型" prop="sbXytype">
          <el-input v-model="form.sbXytype" placeholder="协议类型http mqtt" :disabled="formFlag" />
        </el-form-item>
        <el-form-item label="数据类型" prop="sbTcdatatype">
          <el-input v-model="form.sbTcdatatype" placeholder="数据类型txt json" :disabled="formFlag" />
        </el-form-item>
        <el-form-item label="是否启用" prop="sbIsqy">
          <el-select v-model="form.sbIsqy" placeholder="请选择是否启用">
            <el-option
              v-for="dict in tc_qyzt"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="连接节点" prop="sbJiedian">
          <el-input v-model="form.sbJiedian" placeholder="请输入连接节点" :disabled="formFlag" />
        </el-form-item>
		
		
		
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
	<!-- 绑定项目对话框 -->
	<el-dialog :title="title2" v-model="open2" width="500px" append-to-body>
	  <el-form ref="shebeiRef2" :model="form"  label-width="400px">
		
		<el-divider content-position="center" style="word-spacing: normal;">设备：{{form.sbClientid}}</el-divider>
		
		<el-table :data="tcProjectList" @selection-change="handleTcProjectTpSelectionChange" ref="tcProjectTpRef" max-height="400">
		  <el-table-column type="selection" width="50" align="center" prop="id" />
			<el-table-column type="index" label="序号" width="55" />
		  <el-table-column label="名称" align="center" prop="xmMc"/>
		</el-table>
		
		
	  </el-form>
	  <template #footer>
	    <div class="dialog-footer">
	      <el-button type="primary" @click="submitForm2">确 定</el-button>
	      <el-button @click="cancel2">取 消</el-button>
	    </div>
	  </template>
	</el-dialog>
	
	
  </div>
</template>

<script setup name="Shebei">
import { checkPermi, checkRole } from "@/utils/permission"; // 1. 导入权限判断函数
import { listShebei, getShebei, delShebei, addShebei, updateShebei,updateShebeiState,sbtongbu } from "@/api/tc/shebei";
import { listDept } from "@/api/system/dept";
import { listProject} from "@/api/tc/project";
import useUserStore from '@/store/modules/user'
var userStore=useUserStore();
// console.log(userStore.id)

const { proxy } = getCurrentInstance();
const { tc_qyzt, tc_zxzt } = proxy.useDict('tc_qyzt', 'tc_zxzt');

const tcProjectTpRef =  ref(null);
const shebeiList = ref([]);
const tcProjectList = ref([]);
const shebeiProjectList = ref([]);
const open = ref(false);
const open2 = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const title2 = ref("");
const checkedTcProjectSp = ref([]);
// const tmpGetPar=ref({"pageNum": 1,"pageSize": 999});
const formFlag=ref(false);
const tmpParm={pageNum: 1,pageSize: 500};
const dept_self = ref([]);
const isXxidFlag=ref(false);
const tmpProPar={pageNum: 1,pageSize: 999,xmStatus:'1'};

const toggleSelection = (rows) => {
	      // proxy.$refs["tcProjectTpRef"].toggleRowSelection(row);
			// console.log(proxy.$refs["tcProjectTpRef"])  
		if (rows) {
			// console.log(tcProjectTpRef.value)  
			// console.log(proxy.$refs["tcProjectTpRef"])  
			rows.forEach((row) => {
			  // TODO: improvement typing when refactor table
			  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
			  // @ts-expect-error
			  if(tcProjectTpRef.value!=null){
				  // console.log(row)
				  for(let i of tcProjectList.value){
					  if(i.id == row.projectid) tcProjectTpRef.value.toggleRowSelection(i,true);
				  }
				}
			})
		} else {
			// tcProjectTpRef.value!.clearSelection()
			if(tcProjectTpRef.value!=null){
				tcProjectTpRef.value.clearSelection();//清空复选框
			}
		}
	

}


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sbClientid: null,
    sbLoginuser: null,
    sbTctype: null,
    sbIszx: null,
    sbIsqy: '1',
    sbXytype: null,
    sbTcdatatype: null,
    sbIsdel: null,
    sbJiedian: null,
    sbCreatetime: null,
    sbXxid: null,
    sbName: null
  },
  rules: {
    sbClientid: [
      { required: true, message: "客户端ID不能为空", trigger: "blur" }
    ],
    sbLoginuser: [
      { required: true, message: "登录用户不能为空", trigger: "blur" }
    ],
    sbName: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    sbIsqy: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);


 onMounted(() => {
      // console.log('组件已经挂载')
	 //  nextTick(() => {
	 //        // proxy.$refs["tcProjectTpRef"].toggleRowSelection(row);
		// console.log(proxy.$refs["tcProjectTpRef"])
	 //  });
	  // getList();
	  getDeptInfo()
	  getProjectList();
 })
 
 function getDeptInfo(){
 		// console.log(userStore.user)
 		if(checkRole(['admin','common'])){
 			listDept(tmpParm).then(response => {
 			  	response.data.forEach(function (element) {
 			  	  // 遍历数组，对每个元素进行操作
 				   if(element.xxlevel !=null && element.xxlevel != ''){
 						dept_self.value.push({"value":element.deptId,"label":element.deptName});
 				   }
 			  	});
 				queryParams.value.sbXxid=dept_self.value[0].value;
 				getList();
 			});
 			isXxidFlag.value=false;
 		}else{
 			dept_self.value.push({"value":userStore.user.deptId,"label":userStore.user.dept.deptName});
 			queryParams.value.sbXxid=dept_self.value[0].value;
 			isXxidFlag.value=true;
 			getList();
 		}
 }
 
 
/** 查询体测项目列表 */
function getProjectList() {
  loading.value = true;
  listProject(tmpProPar).then(response => {
    tcProjectList.value = response.rows;
    loading.value = false;
  });
}
/** 查询设备列表 */
function getList() {
  loading.value = true;
  if(checkRole(['admin','common'])){
    // queryParams.value.sbXxid=null;
  }else{
    queryParams.value.sbXxid=userStore.user.deptId;
  }
  listShebei(queryParams.value).then(response => {
    shebeiList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
// 取消按钮
function cancel2() {
  open2.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    sbClientid: null,
    sbLoginuser: null,
    sbTopic: null,
    sbTctype: null,
    sbIszx: null,
    sbIsqy: null,
    sbXytype: null,
    sbTcdatatype: null,
    sbIsdel: null,
    sbJiedian: null,
    sbCreatetime: null,
    sbXxid: null,
    sbName: null
  };
  shebeiProjectList.value = [];
  checkedTcProjectSp.value=[];
  toggleSelection();
  proxy.resetForm("shebeiRef");
  proxy.resetForm("shebeiRef2");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleTB() {
	let deptid=queryParams.value.sbXxid;
	if(deptid==null || deptid==""){
		proxy.$modal.msgError("获取参数错误");
	}else{
		loading.value = true;
		sbtongbu({"deptid":deptid}).then(response => {
		  console.log(response)
		  proxy.$modal.msgSuccess(response.msg);
		  loading.value = false;
			handleQuery();
		}).catch(error => {
			// console.log('I catch:', error);
			loading.value = false;
		})
		// proxy.$modal.msgSuccess("暂未开发");
	}
}

/** 新增按钮操作 */
function handleAdd() {
	formFlag.value=false;
  reset();
  open.value = true;
  title.value = "添加设备";
}

/** 修改按钮操作 */
function handleUpdate(row) {
	formFlag.value=true;
  reset();
  const _id = row.id || ids.value
  getShebei(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改设备";
  });
}

/** 绑定项目按钮操作 */
function handleUpdate2(row) {
  reset();
  const _id = row.id || ids.value
  getShebei(_id).then(response => {
	console.log(response.data)
    form.value = response.data;
    open2.value = true;
    title2.value = "绑定项目";
	
	nextTick(() => {
	  // console.log(tcProjectTpRef.value)
	  
		toggleSelection(response.data.shebeiProjectList);
	});
  });
}
/** 同步状态按钮操作 */
function handleUpdateState(row) {
	// console.log(row)
	// console.log(list)
	// let data={"clientid":row.sbClientid};
    open.value = false;
	updateShebeiState(row).then(response => {
		// console.log(response)
		proxy.$modal.msgSuccess("同步成功");
		for (let i = 0; i < shebeiList.value.length; i++) {
		    if(response.data.id==shebeiList.value[i].id){
				shebeiList.value[i]=response.data;
				return;
			}
		}
		
		open.value = false;
	});
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["shebeiRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateShebei(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addShebei(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 绑定项目按钮 */
function submitForm2() {
  proxy.$refs["shebeiRef2"].validate(valid => {
    if (valid) {
		form.value.shebeiProjectList=checkedTcProjectSp.value
		console.log(form.value)
        updateShebei(form.value).then(response => {
          proxy.$modal.msgSuccess("绑定成功");
          open2.value = false;
          getList();
        });
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除设备编号为"' + row.sbClientid + '"的数据项？').then(function() {
    return delShebei(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
/** 复选框选中数据 */
function handleTcProjectTpSelectionChange(selection) {
  // console.log(selection);
  // checkedTcProjectTp.value = selection.map(item => item.id)
  checkedTcProjectSp.value = selection.map(item => {return {"sbid":null,"projectid":item.id}});
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('tc/shebei/export', {
    ...queryParams.value
  }, `shebei_${new Date().getTime()}.xlsx`)
}

function clitendidInput(e){
	form.value.sbTopic='tcxt/'+e+'/dev';
}

</script>
<style>
	/* 添加CSS样式，防止单元格内的文本换行 */
	.el-table .cell {
	  white-space: nowrap;
	}
</style>